import React from 'react';
import Top from '../../top/index.js';
import Nav from '../../nav/index.js';
import '../serviceSeller/seller.css'
import {Link} from 'react-router-dom';
import SelectAddress from './../../common/select_address/index.js';
import {DatePicker,Select,Input,Button,Table,Dialog,Radio,Checkbox,MessageBox,Form,Pagination} from 'element-react';
import axios from 'axios'
import util from '../../../assets/js/util.js';

class Deliverygoods extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            substationOptions:[{label:'请选择',value:0}], //分站选项
            packageOptions:[{label:'请选择',value:0}], //分拣中心选项
            dialogVisible2: false,
            dialogVisible3: false,
            pageStart:'',
            pageEnd:'',
            exportValue:1,
            exportFields:["分站", "分拣中心", "订单编号", "回收日期", "客户手机号", "总重量", "总金额", "支付方式", "订单状态", "品类重量", "品类"],
            totalPage:'', //总页数
            curPage:1, //当前页
            size:20,
            total:'',
            pageNum: '',
            pageSize: '',
            substationId:'',//分站id
            recycleOrderList: [], //表格数据
            packageId: '', //分拣中心value
            houseOptions: [{label:'请选择',value:0}], //服务亭选项
            houseId: '', //服务亭value
            startDate: null,//开始时间
            endDate: null,//结束时间
            recyclePriceStart:'',//订单金额开始
            recyclePriceEnd:'',//订单金额结束
            orderNum:'',//订单号
            payType:'',//支付类型
            orderStatusOptions: [{
                value: '',
                label: '请选择'
            }, {
                value: '1',
                label: '已提交'
            }, {
                value: '2',
                label: '已付款'
            },{
                value: '6',
                label: '已取消'
            }],
            //弹出框
            orderStatusValue:'', //订单状态选中值
            checkboxData:[{ //导出字段数据
                name:'分站',
                type:'substationName'
            },{
                name:'分拣中心',
                type:'packageName'
            },{
                name:'订单编号',
                type:'orderNum'
            },{
                name:'回收日期',
                type:'ctime'
            },{
                name:'客户手机号',
                type:'userMobile'
            },{
                name:'总重量',
                type:'netWeight'
            },{
                name:'总金额',
                type:'recyclePrice'
            },{
                name:'支付方式',
                type:'payType'
            },{
                name:'订单状态',
                type:'status'
            },{
                name:'品类重量',
                type:'weight'
            },{
                name:'品类',
                type:'recycleTypeTitle'
            }],
            value: 1,
            //弹出框
            columns: [
                {
                    label: "序号",
                    width: 180,
                    type: 'index'
                },
                {
                    label: "分站",
                    prop: "substationName",
                    width: 160,
                    render: function(data){
                        return (
                            <span>
							<span>{data.substationName}</span>
						</span>)
                    }
                },
                {
                    label: "分拣中心",
                    prop: "package",
                    width: 150,
                    render: function(data){
                        return (
                            <span>
							<span>{data.packageName}</span>
						</span>)
                    }
                },
                {
                    label: "订单编号",
                    prop: "number",
                    width: 200,
                    render: function(data){
                        return (
                            <span>
							<span title={data.orderNum}>{data.orderNum}</span>
						</span>)
                    }
                },
                {
                    label: "回收日期",
                    prop: "time",
                    width: 180,
                    render: function(data){
                        return (
                            <span>
                            <span>{util.getDateTime(data.ctime)}</span>
						</span>)
                    }
                },
                {
                    label: "客户手机号",
                    prop: "phone",
                    width: 150,
                    render: function(data){
                        return (
                            <span>
							<span>{data.userMobile}</span>
						</span>)
                    }
                },

                {
                    label: "总重量（KG）",
                    prop: "totalWeight",
                    width: 150,
                    render: function(data){
                        return (
                            <span>
							<span>{data.netWeight/1000}</span>
						</span>)
                    }
                },
                {
                    label: "总金额（元）",
                    prop: "totalMany",
                    width: 150,
                    render: function(data){
                        return (
                            <span>
							<span>{data.recyclePrice/100}</span>
						</span>)
                    }
                },
                {
                    label: "支付方式",
                    prop: "order",
                    width: 120,
                    render: function(data){
                        return (
                            <span>

                                <span>{util.setPayType(data.payType)}</span>
						</span>)
                    }
                },
                {
                    label: "订单状态",
                    prop: "status",
                    width: 120,
                    render: function(data){
                        return (
                            <div>
                                <span>{util.setPackageOrderStatus(data.status)}</span>
                            </div>
                        )
                    }
                },

                {
                    label: "操作",
                    prop: "handle",
                    width: 160,
                    render:( row, column,index )=>{
                        return(
                            <span>
                                <Link to={'/viewo/' + row.orderNum} className="lable" target="_blank"><span></span>查看</Link>
                                <Link to={'/track/' + row.orderNum} className="lable" target="_blank"><span></span>轨迹</Link>
                            </span>
                        )
                    }
                }
            ]
        }
    };
    //弹出框
    onChange(value) {
        this.setState({ value });
    };

    //请求数据
    componentDidMount() {
        //请求列表
        this.gitList(1);
        //二级联动
        this.getAllId();
    };

    // 获取所有分站
    getAllId() {
        //数据获取
        axios.post('count/count/subsandpkgs').then((res) => {
            // console.log(res);
            //分站列表
            let substationOptions = new Array(res.data.data.length);

            res.data.data.forEach((item, index) => {
                substationOptions[index] = {
                    value: item.id,
                    label: item.name
                }
            });
            substationOptions.unshift({value:"",label:"请选择分站"});
            this.setState({substationOptions:substationOptions})

        }).catch((err) => {
            console.log(err);
        });
    }

    //分站change事件
    substationChange = (val, option) => {
        this.setState({substationId: val});
        var params = new URLSearchParams();
        params.append('subId', val);
        axios.post('count/count/selectpkgsbysubid', params)
            .then((res) => {
                let packageOptions = new Array(res.data.data.length);
                res.data.data.forEach((item, index) => {
                    packageOptions[index] = {
                        value: item.id,
                        label: item.siteName
                    }
                });
                packageOptions.unshift({value:"",label:"请选择分拣中心"});
                console.log(packageOptions);
                this.setState({packageOptions: packageOptions})
            })
            .catch((err) => {
                console.log(err)
            });
    };

    //分拣中心change事件
    pkgstationChange = (val, option) => {
        this.setState({packageId: val});

    };

    //请求列表
    gitList(curPage) {
        let params = new URLSearchParams();
        let startDate,endDate;

        if(this.state.startDate){
            startDate = util.formatDate(this.state.startDate);
        }else{
            startDate = '';
        }
        if(this.state.endDate){
            endDate = util.formatDate(this.state.endDate);
        }else{
            endDate = '';
        }
        params.append('substationId', this.state.substationId);
        params.append('packageId',this.state.packageId );
        params.append('payType',  this.state.payType);
        params.append('recyclePriceStart', this.state.recyclePriceStart);
        params.append('recyclePriceEnd',  this.state.recyclePriceEnd);
        params.append('page', curPage);
        params.append('size', 20);
        params.append('orderNum', this.state.orderNum);
        params.append('startDate', startDate);
        params.append('endDate', endDate);
        params.append('status', this.state.orderStatusValue);
        axios.post('/count/sumpackage/getRorPackage',params).then((data) => {
            let temp = [];
            let res = data.data;
            if (res.code == 0) {
                this.setState({
                    curPage:res.data.curPage,
                    totalPage:res.data.totalPage,
                    recycleOrderList: res.data.recycleOrderList,
                    total:res.data.total
                })
            }else if(res.code == -111){
                MessageBox.alert(res.msg);
            } else {
                this.props.history.push('/login')
            }
        }).catch((e) => {
            console.log(e)
        })
    };

    onChange(key,value) {
        this.state[key] = value;
        this.forceUpdate();
    }

    //搜索
    search() {
        this.gitList(1);
    }
    //选择导出字段
    selectCheckbox(e){
        this.setState({
            exportFields: e
        })
    }
    //确定导出
    exportSure(){
        var _page = '';
        var fileds = [];
        let pageEnd='';

        if(this.state.exportValue == 1){
            _page = '';
        }else if(this.state.exportValue == 2){
            _page = this.state.curPage;
        }else if(this.state.exportValue == 3){
            _page = this.state.pageStart;
            pageEnd = this.state.pageEnd;
        }

        let checkboxData = this.state.checkboxData;
        let exportFields = this.state.exportFields;
        checkboxData.forEach((item,index)=>{
            exportFields.forEach((subItem,subIndex)=>{
                if(item.name == subItem){
                    fileds.push(item.type)
                }
            })
        })

        if(fileds.length < 2) return alert('请至少勾选两项');
        let startDate,endDate;

        if(this.state.startDate){
            startDate = util.formatDate(this.state.startDate);
        }else{
            startDate = '';
        }
        if(this.state.endDate){
            endDate = util.formatDate(this.state.endDate);
        }else{
            endDate = '';
        }

        window.open('/count/sumpackage/downloadPackagerecycle?page=' + _page + '&pageEnd=' + pageEnd +  '&substationId=' + this.state.substationId +  '&packageId=' + this.state.packageId +  '&payType=' + this.state.payType +
            '&recyclePriceStart=' + this.state.recyclePriceStart + '&recyclePriceEnd=' + this.state.recyclePriceEnd +  '&orderNum=' + this.state.orderNum +  '&startDate=' + startDate +  '&endDate=' + endDate +  '&status=' + this.state.orderStatusValue + '&fields=' + fileds.join(','));
    }

    //导出弹框
    export(){
        this.setState({
            dialogVisible3: true
        })
    };
    //请求分页数据
    currentPageChange(value){
        //请求当前页
        this.gitList(value);
    };

    // 选择全部记录还是当前页记录
    onExportChange(e) {
        this.setState({
            exportValue: e
        });
    }

    render(){
        const {value1} = this.state;
        return(
            <div className="main-package">
                <Top />
                <Nav delivery="active"/>
                <div className="containerN">

                    {/*二级联动*/}
                    {/*select选择器*/}
                    <div className="box add">
                        <span className="demo width">分站：</span>
                        <SelectAddress
                            value='请选择分站'
                            options={this.state.substationOptions}
                            clsname="sub"
                            selChange={this.substationChange}
                        ></SelectAddress>
                    </div>
                    <div className="box add">
                        <span className="demo width">分拣中心：</span>
                        <SelectAddress
                            value='请选择分拣中心'
                            options={this.state.packageOptions}
                            clsname='sub'
                            selChange={this.pkgstationChange}
                        ></SelectAddress>
                    </div>
                    {/*二级联动*/}

                    {/*input输入框*/}
                    <div className="box input add">
                        <span className="demo width">订单编号：</span>
                        <Input placeholder="请输入内容" value={this.state.orderNum} onChange={this.onChange.bind(this,'orderNum')} />
                    </div>
                    {/*input输入框*/}
                    <div className="box inputone add">
                        <span className="demo width">支付金额：</span>
                        <Input placeholder="请输入内容" maxlength="10" onChange={this.onChange.bind(this,'recyclePriceStart')}/><span className="demo">至</span>
                        <Input placeholder="请输入内容" maxlength="10" onChange={this.onChange.bind(this,'recyclePriceEnd')}/><span className="demo">元</span>
                    </div>
                    {/*select选择器*/}
                    <div className="box add">
                        <span className="demo width">订单状态：</span>
                        <Select value={this.state.value} clearable={true} onChange={this.onChange.bind(this,'orderStatusValue')}>
                            {
                                this.state.orderStatusOptions.map(el => {
                                    return <Select.Option key={el.value} label={el.label} value={el.value} />
                                })
                            }
                        </Select>

                    </div>
                    {/*日期*/}
                    <div className="source boxone box_one">
                        <div className="block">
                            <span className="demo width">日期：</span>
                            <DatePicker
                                value={this.state.startDate}
                                placeholder="选择日期"
                                onChange={date=>{
                                    this.setState({startDate: date})
                                }}
                            />
                            <span className="demo">至 </span>
                            <DatePicker
                                value={this.state.endDate}
                                placeholder="选择日期"
                                onChange={date=>{
                                    this.setState({endDate: date})
                                }}
                            />
                        </div>
                    </div>
                    {/*button*/}
                    <div className="lastBox">
                        <Button onClick={()=>this.search()}><i class="el-icon-search mr-6"></i>搜索</Button>
                        <Button onClick={this.export.bind(this)}><i class="el-icon-upload mr-6"></i>导出</Button>
                        <Dialog title = "导出" visible={ this.state.dialogVisible3 }
                                onCancel={ () => this.setState({ dialogVisible3: false }) }>

                            <Dialog.Body>
                                <Form model={this.state.form}>

                                    <div class='export_one'>
                                <Form.Item label="导出为" >
                                         <Input value='excel' />
                                    </Form.Item>
                                
                                </div>
                                    <Form.Item>
                                        <Radio value="1" checked={this.state.exportValue === 1}
                                               onChange={this.onExportChange.bind(this)}>全部记录</Radio>
                                        <Radio value="2" checked={this.state.exportValue === 2}
                                               onChange={this.onExportChange.bind(this)}>当前页记录</Radio>

                                        <Radio value="3" checked={this.state.exportValue === 3}
                                               onChange={this.onExportChange.bind(this)}>
                                            <span >从</span>
                                            <Input className="exportInput"  onChange={(el)=>{this.setState({pageStart:el})}}/><span>至</span>
                                            <Input className="exportInput"  onChange={(el)=>{this.setState({pageEnd:el})}}/><span>页</span>
                                        </Radio>

                                    </Form.Item>
                                    <div class='export_one'>

                                    <Form.Item label="导出字段">

                                    </Form.Item>
                                    </div>

                                    <Form.Item>
                                        <div className="check">
                                            <Checkbox.Group value={this.state.exportFields} onChange={ this.selectCheckbox.bind(this) }>
                                                {
                                                    this.state.checkboxData.map((item,index)=>{
                                                        return <Checkbox key={index} label={item.name}></Checkbox>
                                                    })
                                                }
                                            </Checkbox.Group>
                                        </div>
                                    </Form.Item>
                                </Form>
                            </Dialog.Body>

                            <Dialog.Footer className="dialog-footer">
                                <Button className="can" onClick={ () => this.setState({ dialogVisible3: false }) }>取 消</Button>
                                <Button className="sur" type="primary" onClick={ this.exportSure.bind(this) }>确 定</Button>
                            </Dialog.Footer>
                        </Dialog>

                    </div>
                    {/*表格*/}
                    <div className='tablebar'>
                        <Table
                            style={{width: '100%'}}
                            columns={this.state.columns}
                            data={this.state.recycleOrderList}
                            border={true}
                        />
                        {<Pagination
                            style={this.state.total == 0 ? {display:'none'} : {display:'block'}}
                            layout="total, prev, pager, next, jumper"
                            total={this.state.total}
                            pageSize={20}
                            onCurrentChange={this.currentPageChange.bind(this)}
                        />}
                    </div>
                </div>
            </div>
        );
    }
}

export default Deliverygoods;